package com.yxhl.zoume.core.main.presenter;

import android.content.Context;
import android.os.Environment;

import com.yxhl.zoume.common.presenter.IPresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.main.ui.view.UpdateAppView;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.updateapp.UpdateAppUseCase;
import com.yxhl.zoume.utils.AppInfoUtils;
import com.yxhl.zoume.utils.LOG;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.inject.Inject;

import okhttp3.ResponseBody;

/**
 * Created by sugarya on 16/5/13.
 */
public class UpdateAppPresenter implements IPresenter {

    private static final String TAG = "UpdateAppPresenter";

    @Inject
    UpdateAppUseCase mUpdateAppUseCase;

    private UpdateAppView mUpdateAppView;
    private File mTargetFile;
    private Context mContext;

    @Inject
    public UpdateAppPresenter(Context context) {
        mContext = context;
        mTargetFile = getDownloadFile(context);
    }

    public void downloadZouMeApp(String fileUrl) {
        mUpdateAppUseCase.downloadApp(fileUrl, new ZMSubscriber<ResponseBody>() {
            @Override
            public void onCompleted() {
                super.onCompleted();
                LOG.e(TAG, "onCompleted");
                mUpdateAppView.renderDataOnCompleted();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mUpdateAppView.renderDataOnError();
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                super.onNext(responseBody);
                writeResponseBodyToDisk(responseBody);
            }
        });
    }

    private boolean writeResponseBodyToDisk(ResponseBody body) {
        try {

            InputStream inputStream = null;
            FileOutputStream outputStream = null;

            try {


                byte[] buffer = new byte[4096];

                long fileSize = body.contentLength();
                float fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(mTargetFile);

                while (true) {
                    int read = inputStream.read(buffer);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(buffer, 0, read);

                    fileSizeDownloaded += read;

                    float ratio = fileSizeDownloaded / fileSize;

                    LOG.e(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize + "  ratio=" + ratio);

                    mUpdateAppView.renderDataOnSuccess(ratio, mTargetFile);

                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 新版本APK存放路径
     *
     * @param context
     * @return
     */
    public File getDownloadFile(Context context) {
        File externalCacheDir = null;
        boolean hasExternalStorage = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED);
        if (hasExternalStorage) {
            if (context != null) {
                externalCacheDir = context.getExternalCacheDir();
            } else {
                externalCacheDir = Environment.getExternalStorageDirectory();
            }
        } else {
            if (context != null) {
                externalCacheDir = context.getCacheDir();
            }
        }

        if (!externalCacheDir.exists()) {
            if (externalCacheDir.isDirectory()) {
                externalCacheDir.mkdirs();
            }
        }
        // TODO: 16/7/12 存放apk的路径确认下是不是放在cache分类下(放在File分类是不是更合理)
//        File targetDir = new File(externalCacheDir,"apkoutresult");
//        if(!targetDir.exists()){
//            if(targetDir.isDirectory()){
//                targetDir.mkdirs();
//            }
//        }

        File targetFile = new File(externalCacheDir + "/zoume_v" + AppInfoUtils.getVersionName() + ".apk");
//        if(!targetFile.exists()){
//            try {
//                targetFile.createNewFile();
//                targetFile.setWritable(true);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        LOG.e(TAG, "targetFile path =" + targetFile.getAbsolutePath());
        return targetFile;
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {
    }

    @Override
    public void onDestroy() {
        mUpdateAppUseCase.unsubscribe();
    }

    @Override
    public void attachView(BaseView view) {
        if (view instanceof UpdateAppView) {
            mUpdateAppView = (UpdateAppView) view;
        }
    }
}
